package com.gome.ocean.controller.authority;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.gome.ocean.common.utils.ResponsePage;
import com.gome.ocean.dao.model.authority.Function;
import com.gome.ocean.dao.model.authority.MenuRoleVO;
import com.gome.ocean.dao.model.authority.MenuSource;
import com.gome.ocean.dao.model.authority.Module;
import com.gome.ocean.dao.model.authority.Role;
import com.gome.ocean.dao.model.authority.RoleMenu;
import com.gome.ocean.dao.model.authority.User;
import com.gome.ocean.service.authority.FunctionService;
import com.gome.ocean.service.authority.MenuRoleService;
import com.gome.ocean.service.authority.RoleService;
import com.gome.ocean.service.base.BaseController;

/**
 * @author liyuefeng
 */
@Controller
public class MenuRoleController extends BaseController {

    private static final Logger LOG = LoggerFactory.getLogger(MenuRoleController.class);

    @Autowired
    private MenuRoleService menuRoleService;
    @Autowired
    private FunctionService functionService;
    @Autowired
    private RoleService     roleService;

    @RequestMapping(value = "menuAdmin/toInsertPage", method = RequestMethod.GET)
    public ModelAndView adminPage(ModelAndView mav, HttpServletRequest request) {
        List<MenuRoleVO> menuRoleVOs = menuRoleService.getAllMenu();
        JSONArray array = new JSONArray();
        array = convertListToJsonArray(menuRoleVOs, array);
        mav.getModel().put("menuRoleVOs", array);
        mav.setViewName("authority/menu/menu-insert");
        return mav;
    }

    protected JSONArray convertListToJsonArray(List<MenuRoleVO> menuRoleVOs, JSONArray array) {

        for (MenuRoleVO vo : menuRoleVOs) {
            JSONObject jsonObject = new JSONObject();
            JSONArray jsonArray = new JSONArray();
            jsonObject.put("id", vo.getId());
            jsonObject.put("isLink", vo.getIsLink());
            jsonObject.put("menuName", vo.getMenuName());
            jsonObject.put("IconId", vo.getIconId());
            jsonObject.put("MenuLevel", vo.getMenuLevel());
            jsonObject.put("menuUrl", vo.getMenuUrl());
            jsonObject.put("functionId", vo.getRelationFunction());
            jsonObject.put("menuRoleVOs",
                (!(null == vo.getMenuRoleVOs())
                 && vo.getMenuRoleVOs().size() > 0 ? convertListToJsonArray(vo.getMenuRoleVOs(), jsonArray) : null));
            jsonObject.put("sort", vo.getSort());
            array.add(jsonObject);
        }

        return array;
    }

    @RequestMapping(value = "menuAdmin/toFindPage", method = RequestMethod.GET)
    public ModelAndView adminFindPage(ModelAndView mav, HttpServletRequest request) {
        mav.setViewName("authority/menu/menu-find");
        return mav;
    }

    @RequestMapping(value = "menuAdmin/getMenuInfo", method = RequestMethod.POST)
    @ResponseBody
    public void getMenuInfo(HttpServletRequest request, HttpServletResponse response) {
        Byte level = request.getParameter("level") == null ? 1 : Byte.parseByte(request.getParameter("level"));
        Integer pid = request.getParameter("pid") == null ? 0 : Integer.parseInt(request.getParameter("pid"));

        List<MenuSource> list = menuRoleService.getMenuLevelList(pid, level);
        try {

            response.getWriter().print(JSONArray.toJSONString(list));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            LOG.error("异常信息：" + e.toString());
        }
    }

    @RequestMapping(value = "menuAdmin/getFunctionList", method = RequestMethod.POST)
    @ResponseBody
    public void getFunctionList(HttpServletRequest request, HttpServletResponse response) {
        int pageNum = request.getParameter("pageNum") == null ? 1 : Integer.parseInt(request.getParameter("pageNum"));
        int pageSize = request.getParameter("pageSize") == null ? 0 : Integer
            .parseInt(request.getParameter("pageSize"));
        Page<Function> list = functionService.findAllFunctions(pageNum, pageSize);
        try {

            response.getWriter().print(JSONArray.toJSONString(list));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            LOG.error("异常信息：" + e.toString());
        }
    }

    @RequestMapping(value = "menuAdmin/insertMenuInfo", method = RequestMethod.POST)
    @ResponseBody
    public int insertMenuInfo(HttpServletRequest request, HttpServletResponse response, MenuSource menuSource) {
        Integer result;
        try {
            MenuSource menuSource2 = menuRoleService.findMenuByName(menuSource.getMenuName());
            if (null == menuSource2) {
                result = menuRoleService.saveMenuInfo(menuSource);
                if (result == 1) {
                    return 1;
                } else {
                    return 0;
                }
            } else {
                return 2;
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            LOG.error("异常信息：" + e.toString());
            return 0;
        }

    }

    @RequestMapping(value = "menuAdmin/searchMenuList", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage searchMenuList(HttpServletRequest request) {
        ResponsePage res = new ResponsePage();
        res.setSuccess(false);
        int pageNum = getPageNum();
        int pageSize = getPageSize();
        String name = request.getParameter("menuName");

        try {
            Page<MenuSource> menuSources = null;
            MenuSource menuSource = null;
            if (StringUtils.isBlank(name)) {
                menuSources = menuRoleService.findAllMenu(pageNum, pageSize);
                if (null == menuSources || 0 == menuSources.size()) {
                    return res.setSuccessMsg("未查询到结果");
                }
                return res.setPage(menuSources, "查询成功");

            } else {
                menuSource = menuRoleService.findMenuByName(name);
                menuSources = new Page<MenuSource>();
                menuSources.add(menuSource);
                menuSources.setTotal(1);
                if (menuSource != null) {
                    return res.setPage(menuSources, "查询成功");
                }
                return res.setSuccessMsg("暂无数据");
            }
        } catch (Exception e) {
            LOG.error(e.toString());
            return res.setErrorMsg("没有数据");
        }

    }

    @RequestMapping(value = "menuAdmin/update", method = RequestMethod.POST)
    @ResponseBody
    public int toUpdateMenuInfo(HttpServletRequest request, MenuSource menuSource) {
        int result = menuRoleService.updateByPrimaryKeySelective(menuSource);
        return result;
    }

    @RequestMapping(value = "menuAdmin/toInsertMenuRolePage", method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView toInsertMenuRolePage(ModelAndView mav, HttpServletRequest request,
                                             HttpServletResponse response) {
        List<MenuRoleVO> menuRoleVOs = menuRoleService.getAllMenu();
        mav.getModel().put("menuRoleVOs", menuRoleVOs);
        mav.setViewName("authority/menu/menu-role-insert");
        return mav;
    }

    @RequestMapping(value = "menuAdmin/getAllRole", method = RequestMethod.POST)
    @ResponseBody
    public void getAllRole(HttpServletRequest request, HttpServletResponse response) {

        List<Role> roleList = roleService.getAllRoles();
        try {
            response.getWriter().print(JSONArray.toJSONString(roleList));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            LOG.error(e.toString());
        }
    }

    @RequestMapping(value = "menuAdmin/insertMenuRole", method = RequestMethod.POST)
    @ResponseBody
    public int insertMenuRole(HttpServletRequest request, RoleMenu roleMenu) {
        roleMenu.setStatus((byte) 2);
        int count = menuRoleService.getRoleMenuCountByParam(roleMenu);
        if (count > 0) {
            return 2;
        } else {
            roleMenu.setAddtime(new Date());
            if (menuRoleService.saveMenuRoleInfo(roleMenu) == 1) {
                return 1;
            } else {
                return 0;
            }
        }
    }

    @RequestMapping(value = "menuAdmin/findMenuRole", method = RequestMethod.GET)
    public ModelAndView toFindMenuRolePage(ModelAndView mav, HttpServletRequest request) {
        mav.setViewName("authority/menu/menu-role-find");

        List<MenuRoleVO> menuRoleVOs = menuRoleService.getAllMenu();
        mav.getModel().put("menuRoleVOs", menuRoleVOs);
        return mav;
    }

    @SuppressWarnings("null")
    @RequestMapping(value = "menuAdmin/findMenuRoleByRoleId", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage findMenuRoleByRoleId(HttpServletRequest request, HttpServletResponse response) {
        ResponsePage res = new ResponsePage();
        res.setSuccess(false);
        Integer roleId = Integer.parseInt(request.getParameter("roleId"));
        try {
            Page<MenuRoleVO> menuRoleVOPage = null;
            if (StringUtils.isBlank(request.getParameter("roleId"))) {
                res.setErrorMsg("查询失败，请输入roleid");
                return res;
            } else {
                List<RoleMenu> roleMenus = menuRoleService.getRoleMenusByRoleId(roleId);
                if (roleMenus != null && roleMenus.size() > 0) {
                    res.setSuccess(true);
                    res.setJustList(roleMenus, "查询成功");
                    return res;
                }
            }
            return res.setSuccessMsg("没有数据");
        } catch (Exception e) {
            LOG.error(e.toString());
            return res.setErrorMsg("没有数据");
        }
    }

    @RequestMapping(value = "menuAdmin/updateMenuRoleInfo", method = RequestMethod.POST)
    @ResponseBody
    public int updateMenuRoleInfo(HttpServletRequest request, RoleMenu roleMenu) {
        if (menuRoleService.updateByRoleMenuPrimaryKeySelective(roleMenu) == 1) {
            return 1;
        } else {
            return 0;
        }
    }

    @RequestMapping(value = "menuAdmin/getAllModule", method = RequestMethod.POST)
    @ResponseBody
    public void getAllModule(HttpServletRequest request, HttpServletResponse response) {
        List<Module> moduleList = menuRoleService.getAllModule();
        try {
            response.getWriter().print(JSONArray.toJSONString(moduleList));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            LOG.error(e.toString());
        }
    }

    @RequestMapping(value = "menuAdmin/getFunctionByModuleId", method = RequestMethod.POST)
    @ResponseBody
    public void getFunctionByModuleId(HttpServletRequest request, HttpServletResponse response) {
        Long moduleId = Long.valueOf(request.getParameter("moduleId"));
        List<Function> functions = menuRoleService.getFunctionGroupByModuleId(moduleId);
        try {
            response.getWriter().print(JSONArray.toJSONString(functions));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            LOG.error(e.toString());
        }
    }

    @RequestMapping(value = "menuAdmin/insertMenuRoleList", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage insertMenuRoleList(HttpServletRequest request, Integer roleId, String menuIds) {
        ResponsePage response = getResponsePage();
        String mrArray = menuIds.replace("\'", "\"");
        JSONArray menuRoleArray = JSONArray.parseArray(menuIds);
        List<RoleMenu> roleMenus = new ArrayList<RoleMenu>();
        for (Object object : menuRoleArray) {
            RoleMenu roleMenu = new RoleMenu();
            Integer menuId = JSONObject.parseObject(object.toString()).getInteger("menuId");
            roleMenu.setMenuId(menuId);
            String functionDetail = JSONObject.parseObject(object.toString()).getString("functionDetail");
            roleMenu.setFunctionDetail(functionDetail);
            roleMenu.setRoleId(roleId);
            roleMenu.setAddtime(new Date());
            roleMenu.setStatus((byte) 2);
            roleMenus.add(roleMenu);

        }
        try {
            boolean flagDelete = menuRoleService.deleteMenuRoleByRoleId(roleId);
            if (flagDelete) {
                boolean flagInsert = menuRoleService.insertMenuRoleList(roleMenus);
                if (flagInsert) {
                    response.setSuccess(true);
                    return response.setSuccessMsg("修改角色及其相关关系的菜单成功");
                } else {
                    response.setSuccess(false);
                    return response.setErrorMsg("批量添加过程中发生失败，请联系管理员");
                }

            }
            response.setSuccess(false);
            return response.setErrorMsg("删除过程中发生失败，请联系管理员");

        } catch (Exception e) {
            // TODO Auto-generated catch block
            LOG.error(e.getMessage(), e);
            response.setSuccess(false);
            return response.setErrorMsg("新建关系过程中发生异常");
        }
    }

    @RequestMapping(value = "menuAdmin/getRoleFunction", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage getRoleFunction(HttpServletRequest request) {
        ResponsePage response = getResponsePage();
        Long functionId = Long.valueOf(request.getParameter("functionId"));
        Function function = functionService.findFunctionById(functionId);
        Integer moduleId = function.getModule();
        User user = this.getCurrentUserObj();
        Long roleId = Long.valueOf(request.getParameter("roleId"));
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("moduleId", moduleId);
        param.put("roleId", roleId);

        try {
            List<Map<String, Object>> list = menuRoleService.getRoleFunctionList(param);
            if (!(list == null) && list.size() > 0) {
                response.setSuccess(true);
                response.setJustList(list, "查询成功");
                return response;
            } else {
                response.setSuccess(false);
                return response.setErrorMsg("暂无数据");
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            LOG.error(e.getMessage(), e);
            response.setSuccess(false);
            return response.setErrorMsg("查询过程中发生异常");
        }
    }

    @RequestMapping(value = "menuAdmin/getMenuSourceById", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage getMenuSourceById(HttpServletRequest request, HttpServletResponse response) {
        ResponsePage res = new ResponsePage();
        res.setSuccess(false);
        Integer id = Integer.valueOf(request.getParameter("menuSourceId"));
        MenuSource menuSource = menuRoleService.selectByPrimaryKey(id);
        Page<MenuSource> menuSources = new Page<MenuSource>();
        menuSources.add(menuSource);
        menuSources.setTotal(1);

        if (null == menuSources || 0 == menuSources.size()) {
            return res.setSuccessMsg("未查询到结果");
        }

        res.setSuccess(true);
        return res.setPage(menuSources, "查询成功");
    }

    @RequestMapping(value = "menuAdmin/removeMenu", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage removeMenu(HttpServletRequest request) {

        ResponsePage response = new ResponsePage();
        response.setSuccess(false);
        Integer id = Integer.valueOf(request.getParameter("menuSourceId"));
        try {
            menuRoleService.deleteByPrimaryKey(id);
            response.setSuccess(true);
            return response;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            LOG.error(e.getMessage(), e);
            response.setSuccess(false);
            return response;
        }
    }

    @RequestMapping(value = "menuAdmin/batchUpdataMenuSource", method = RequestMethod.POST)
    @ResponseBody
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public ResponsePage batchUpdataMenuSource(HttpServletRequest request) {
        ResponsePage response = new ResponsePage();
        response.setSuccess(false);
        String menuSources = request.getParameter("menuSources");
        List<MenuSource> sources = JSONArray.parseArray(menuSources, MenuSource.class);
        try {
            for (MenuSource menuSource : sources) {
                menuRoleService.updateByPrimaryKeySelective(menuSource);
            }
            response.setSuccess(true);
            return response;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            LOG.error(e.getMessage(), e);
            response.setSuccess(false);
            return response;
        }

    }
}
